package cc.telecomdigital.tdstock.Services;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import cc.telecomdigital.tdstock.Framework.UniqueItem.DeviceInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Tools.CDR_ErDefinition;
import android.content.Context;

public class TDStockReportCDRUsage
{
	public interface ITDStockReportCDRUsage_Result
	{
		void TDStockReportCDRUsage_Response(TDStockReportCDRUsage_Result iResult);
	}

	public class TDStockReportCDRUsage_Result
	{
		public boolean	successfulSend;
		public String  idString;
		public String	descriptMessage;
		public String	statusCode;

		public TDStockReportCDRUsage_Result( boolean iSuccessfulSend, String iIdentification,
									  String iStatus, String iDescriptMessage)
		{
			idString        = iIdentification;
			successfulSend  = iSuccessfulSend;
			descriptMessage = iDescriptMessage;
			statusCode      = iStatus;
		}
	}

	private final String LOG_TAG = "TDStockReportCDRUsage";
	private boolean debugMode = false;

	private Context   ownerContext;
	private String    urlString;

	private String    urlPort;

	private final int SOCKET_TIMEOUT	= 10000;
	private final int CONNECT_TIMEOUT	= 10000;	
	private final int waitNextTrial    = 500;
	private ITDStockReportCDRUsage_Result reporter;

	private String                     idString;
	//Retry is configurable
	private final int              	trialMax = 1;

	// We will construct the url here	
	public TDStockReportCDRUsage(Context iOwnerContext)
	{
		ownerContext = iOwnerContext;
		urlString    = null;
		urlPort 	   = null;
		idString     = null;
	}

	/** Set The CDR Require paramter.  Please note the time is auto-update when it is create
	 * @param iIdentification - String iIdentifier when callback is provided
	 * @param iURL			 - The url param that has %s allow to place in the current time
	 * @param iPortNumber     - Port number for transport
	 */
	public boolean SetCDRUpdateParam(String iIdentification, String iURL, String iPortNumber)
	{
		if (iURL == null)
			return false;

		boolean status;

		status = false;
		try
		{
			URL  urlObject;

			//Perform a testing of the object
			urlObject = new URL(iURL);

			//Set the next sending time and seqNo
//			urlString = String.format( iURL,
//				LS_ClientParamMemory.SimpleDateStringFormatter(Calendar.getInstance().getTime()));
			urlString = iURL;
			urlPort   = iPortNumber;
			idString  = iIdentification;

			if (debugMode)
				TDStockLog.i(LOG_TAG, "SetCDRExtraInformation: " + urlString);
			status = true;
		}
		catch (MalformedURLException ex)
		{
			ex.printStackTrace();
			TDStockLog.e(LOG_TAG, "SetCDRExtraInformation->MalformedURLException: Invalid format");			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			TDStockLog.e(LOG_TAG, "SetCDRExtraInformation: Invalid format");
		}

		return status;
	}
	
	/** Date are sent to server with NO UI Thread reply, since it is very unlikely for UI to
	 * take the response
	 * @param iResponse - Response caller API
	 */
	public void SendRequest( ITDStockReportCDRUsage_Result iResponse)
	{
		reporter = iResponse;

		Thread internalThreadObj;
		internalThreadObj = new Thread()
		{
			@Override
			public void run()
			{
				if (!DeviceInfo.IsNetworkAvailable(ownerContext) || (urlString == null))
				{
					if (reporter != null)
						reporter.TDStockReportCDRUsage_Response( new TDStockReportCDRUsage_Result(false, idString, "", ""));
					return;
				}

				int 					    trialCount;
				TDStockReportCDRUsage_Result result;
				//Now send the result
				HttpClient 			    client;
				HttpGet    			    request;
				HttpParams 			    modParams;

				if (debugMode)
					TDStockLog.i(LOG_TAG, "SendDataSub=>Request: " + urlString);

				client = new DefaultHttpClient();
				request = new HttpGet(urlString);
				modParams = request.getParams();

				// Change the setting
				HttpConnectionParams.setSoTimeout(modParams, SOCKET_TIMEOUT);
				HttpConnectionParams.setConnectionTimeout(modParams, CONNECT_TIMEOUT);
				HttpConnectionParams.setSocketBufferSize(modParams, 8192);		
				request.setParams(modParams);
				
				trialCount = 0;
				while(true)
				{
					result = SendDataSub(idString, client, request);
					//If we did not get the require login information
					if ((result.descriptMessage.equals("")) && (result.statusCode.equals("")) )
					{
						++trialCount;
						if (trialCount < trialMax)
						{
							if (debugMode)
								TDStockLog.i(LOG_TAG, "SendRequest: Retry performed: " + trialCount);
							try
							{
								sleep(waitNextTrial);
							}
							catch(Exception ex)
							{
								TDStockLog.e(LOG_TAG, "SendRequest: Ex=" + ex.toString());
							}
							continue;
						}
					}
					break;
				}
				//Report to the caller
				if (reporter != null)
					reporter.TDStockReportCDRUsage_Response(result);					
			}
		};
		internalThreadObj.setName(LOG_TAG);
		internalThreadObj.start();
	}

	private TDStockReportCDRUsage_Result SendDataSub(String iIdString, HttpClient iClient, HttpGet iRequest)
	{
		String     statusMsg, descriptMessage;

		statusMsg = "";
		descriptMessage = "";
		try
		{
			HttpResponse webResponse;
			StringBuffer contentString;

			webResponse = iClient.execute(iRequest);
			if ((webResponse == null) || (webResponse.getStatusLine().getStatusCode()!= HttpStatus.SC_OK ))
				webResponse.getEntity().getContent().close();
			else
			{
				contentString = CommunicTools.GetWebResponseInStringBuffer(webResponse);													
				statusMsg = CommunicTools.FindXMLStringContent(contentString, "status");
				descriptMessage = CommunicTools.FindXMLStringContent(contentString, "status_desc");
				if (debugMode && !statusMsg.equals(""))
				{
					int value;
					String iStr;
					
					value = Integer.valueOf(statusMsg);
					iStr = CDR_ErDefinition.CDRStatusValueToString(value);
					TDStockLog.i(LOG_TAG, "SendDataSub: " + iStr + ", value=" + statusMsg);
				}					
			}
		}
		catch(SocketTimeoutException e)
		{
			TDStockLog.e(LOG_TAG, "SendDataSub=>SocketTimeoutException: " + e.toString());
			e.printStackTrace();
		}
		catch (ClientProtocolException e)
		{
			TDStockLog.e(LOG_TAG, "SendDataSub=>ClientProtocolException: " + e.toString());
			e.printStackTrace();
		}
		catch (IOException e)
		{
			TDStockLog.e(LOG_TAG, "SendDataSub=>IOException: " + e.toString());
			e.printStackTrace();
		}
		catch (Exception e)
		{
			TDStockLog.e(LOG_TAG, "SendDataSub=>Exception: " + e.toString());
			e.printStackTrace();
		}

		return new TDStockReportCDRUsage_Result(true, iIdString, statusMsg, descriptMessage);		
	}
}

	